using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UMC.Data;
using UMC.Web;
using UMC.Web.UI;
using UMC.WorkFlow.Entities;

namespace UMC.WorkFlow
{


    [Apiumc("WorkFlow", "CheckControl", Auth = WebAuthType.Admin, Desc = "表单可视")]
    public class WorkFlowCheckControlActivity : WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var SId = this.AsyncDialog("Id", g =>
            {
                this.Prompt("请输入Id");
                return this.DialogValue("none");
            });

            var Task = Utility.UInt64Parse(this.AsyncDialog("Task", g =>
            {
                this.Prompt("请输入工作流");
                return this.DialogValue("none");
            })).Value;

            var design = DataFactory.Instance().TaskForm(Task);
            // UMC.WorkFlow.TaskRuntime.Database.ObjectEntity<TaskForm>()
            //     .Where.And(new TaskForm {   TaskId = Task }).Entities.Single();
            if (design == null)
            {
                this.Prompt("无此流程设计");
            }
            else
            {
                Task = design.TaskId.Value;
            }

            // var taskInstance = UMC.Data.JSON.Deserialize<TaskInstance>(design.Context);



            var Item = Utility.UInt64Parse(this.AsyncDialog("Item", g =>
           {
               //    var limit = this.AsyncDialog("limit", "none");

               //    if (limit == "none")
               //    {
               //        this.Context.Send(new UISectionBuilder(request.Model, request.Command, new UMC.Web.WebMeta().Put("Id", SId).Put("Task", Task))

               //            .RefreshEvent("WorkFlow.CheckControl")
               //                .Builder(), true);
               //    }

               var entity = HotCache.Find(new TaskFormControl { TaskId = design.TaskId }, false, 0, 10000, out var _).OrderBy(r => r.Seq ?? 0);
               //    entity.Order.Asc(new TaskFormControl { Seq = 0 });

               var ctls = new List<TaskFormControl>();
               var ids = new List<ulong>();
               Utility.Each(entity, dr =>
               {
                   ctls.Add(dr);
                   ids.Add(dr.ItemId.Value);
               });

               var checks = new List<TaskCheckContorl>();
               if (ids.Count > 0)
               {
                   checks.AddRange(HotCache.Find(new TaskCheckContorl { ShapeId = SId }, "ItemId", ids));
               }
               //    TaskRuntime.Database.ObjectEntity<TaskCheckContorl>()

               //      .Where.And().Equal(new TaskCheckContorl { ShapeId = SId })
               //      .And().In(new TaskCheckContorl { ItemId = ids[0] }, ids.ToArray())
               //      .Entities
               //      .Query(dr => checks.Add(dr));
               var ui = UISection.Create(new UITitle("表单可见设置"));

               if (String.Equals(SId, "default", StringComparison.CurrentCultureIgnoreCase))
               {
                   ui.AddCell('\uf0e8', "流程结点", "默认");
                   //ui.AddCell()
               }
               else
               {

                   var shape = TaskManager.Form(Task).Shapes.Find(s => s.Id == SId);
                   if (shape != null)
                   {
                       ui.AddCell('\uf0e8', "流程结点", String.Format("{1}({0})", shape.Id, shape.Text));
                   }
                   else
                   {
                       ui.AddCell('\uf0e8', "流程结点", "未知");
                   }

               }
               var ucl = ui.NewSection();
               var controls = ctls.FindAll(ck => ck.ForId == 0);
               foreach (var cl in controls)
               {
                   var sCheck = "标准";
                   var sc = checks.Find(k => k.ItemId == cl.ItemId) ?? new TaskCheckContorl() { ContorlMode = UIContorlMode.Normal };
                   switch (sc.ContorlMode)
                   {
                       case UIContorlMode.Normal:
                           sCheck = "标准";
                           break;
                       case UIContorlMode.Edit:
                           sCheck = "编辑";
                           break;
                       case UIContorlMode.Readonly:
                           sCheck = "只读";
                           break;
                       case UIContorlMode.Hidden:
                           sCheck = "隐藏";
                           break;
                       case UIContorlMode.Insert:
                           sCheck = "新增";
                           break;
                   }
                   ucl.AddCell(String.Format("{0}({1})", cl.Caption, cl.Code), sCheck
                       , new UIClick(request.Model, request.Command, new WebMeta().Put("Id", SId).Put("Task", Task).Put("Item", cl.ItemId)));
                   if (cl.Type == ControlType.List)
                   {
                       var controls2 = ctls.FindAll(k => k.ForId == cl.ItemId);

                       foreach (var cl2 in controls2)
                       {
                           sCheck = "标准";
                           var sc2 = checks.Find(k => k.ItemId == cl2.ItemId) ?? new TaskCheckContorl() { ContorlMode = UIContorlMode.Normal };
                           switch (sc2.ContorlMode)
                           {
                               case UIContorlMode.Normal:
                                   sCheck = "标准";
                                   break;
                               case UIContorlMode.Edit:
                                   sCheck = "编辑";
                                   break;
                               case UIContorlMode.Readonly:
                                   sCheck = "只读";
                                   break;
                               case UIContorlMode.Hidden:
                                   sCheck = "隐藏";
                                   break;
                               case UIContorlMode.Insert:
                                   sCheck = "新增";
                                   break;
                           }
                           ucl.AddCell('\uf105', String.Format("{0}({1})", cl2.Caption, cl2.Code), sCheck
                               , new UIClick(request.Model, request.Command, new WebMeta().Put("Id", SId).Put("Task", Task).Put("Item", cl2.ItemId)));



                       }
                   }


               }
               if (controls.Count == 0)
               {
                   ucl.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未配置表单组件").Put("icon", "\uEA05")
                   , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
            new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 

               }
               ui.SendTo(this.Context, "WorkFlow.CheckControl");

           })) ?? 0;

            var formControl = DataFactory.Instance().TaskFormControl(Item);
            // TaskRuntime.Database.ObjectEntity<TaskFormControl>()
            //      .Where.And().Equal(new TaskFormControl { ItemId = Item }).Entities.Single();

            var mdel = Utility.Parse(this.AsyncDialog("ContorlMode", g =>
              {
                  var selt = new UISelectDialog();
                  selt.Title = "控件展示";
                  selt.Options.Put("标准", "Normal").Put("编辑", "Edit").Put("只读", "Readonly").Put("隐藏", "Hidden");
                  if (formControl.Type == ControlType.List)
                  {
                      selt.Options.Add("新增", "Add");
                  }
                  return selt;
              }), UIContorlMode.Normal);
            if (mdel == UIContorlMode.Normal)
            {

                DataFactory.Instance().Delete(new TaskCheckContorl { ItemId = Item, ShapeId = SId });
                // .Entities.Delete();
            }
            else
            {

                // TaskRuntime.Database.ObjectEntity<TaskCheckContorl>()
                // .Where.And().Equal(new TaskCheckContorl { ItemId = Item, ShapeId = SId })
                // .Entities.IFF(e => e.Update(new TaskCheckContorl { ContorlMode = mdel }) == 0, e => 

                DataFactory.Instance().Put(new TaskCheckContorl
                {
                    ItemId = Item,
                    ContorlMode = mdel,
                    ShapeId = SId
                });
            }
            this.Context.Send("WorkFlow.CheckControl", true);
        }


    }
}